package com.icebergteam.warfacewidget.wiki.ui;

import java.util.ArrayList;
import org.jsoup.Jsoup;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.widget.RemoteViews;
import com.icebergteam.warfacewidget.R;
import com.icebergteam.warfacewidget.core.ListViewFactory;
import com.icebergteam.warfacewidget.core.LogManager;
import com.icebergteam.warfacewidget.core.utils.ViewUtils;
import com.icebergteam.warfacewidget.wiki.data.WikiDownloadTask;
import com.icebergteam.warfacewidget.wiki.data.WikiWidgetItem;
import com.icebergteam.warfacewidget.wiki.data.WikiWidgetParser;

public class WikiListViewFactory extends ListViewFactory {
	public static String className = WikiListViewFactory.class
			.getCanonicalName();

	ArrayList<WikiWidgetItem> items = new ArrayList<WikiWidgetItem>();

	private WikiDownloadTask wikiDownloadTask;

	private WikiWidgetParser wikiWidgetParser;
	
	public WikiListViewFactory(Context ctxt, Intent intent) {
		super(ctxt, intent);
		
		 this.wikiWidgetParser = new WikiWidgetParser();
		 this.wikiDownloadTask = new WikiDownloadTask(null, null, WikiActivity.homeWikiHtmlPage, true, false);
		
		String fullHtml;
		try{
			fullHtml = this.wikiDownloadTask.getHtml(WikiActivity.homeWikiHtmlPage).getSecond();
			items = this.wikiWidgetParser.parseXML(Jsoup.parse(fullHtml), -1);
			super.count = items.size();
		}
		catch(Exception e){
			LogManager.LogEA(className, ViewUtils.getErrorMessage(e));
		}

		
	}

	@Override
	public RemoteViews getViewAt(int position) {
		try {
			RemoteViews row = new RemoteViews(context.getPackageName(),
					R.layout.wiki_item_widget_layout);
				WikiWidgetItem item = items.get(position);
				row.setTextViewText(R.id.textView1,
							item.getTitle());
				row.setImageViewUri(R.id.imageView1, Uri.parse(item.getImgSrc()));
			
				Intent i = new Intent();
				i.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1));
				i.putExtra(WikiActivity.KEY_CURRENT_URL, item.getUrl());
				row.setOnClickFillInIntent(R.id.wiki_item_widget_layout, i);
				LogManager.LogEA(className, count, item.getUrl());
			
			
			return row;
		} catch (NumberFormatException e) {
			
		} catch (Exception e) {
			
		}
		return null;
	}
}